using System;
using Audio;
using Bubbles;
using Data;
using Locomotion;
using UnityEngine;

namespace Controls
{
    public class CriticalHitController : MonoBehaviour
    {
        public event Action CriticalHit;

        [SerializeField] private float _minCriticalHitDist = 1f;
        [SerializeField] private AudioClip criticalHitSound;
        [SerializeField] private ParticleSystem criticalEffect;
        
        
        private void OnEnable()
        {
            GroundDetector.AnyCharacterGroundedChanged += GroundDetector_AnyCharacterGroundedChanged;
        }

        private void OnDisable()
        {
            GroundDetector.AnyCharacterGroundedChanged -= GroundDetector_AnyCharacterGroundedChanged;
        }
        
        private void GroundDetector_AnyCharacterGroundedChanged(GroundDetector.GroundChangedEventArgs groundChangedEventArgs)
        {
            CheckCriticalHit(groundChangedEventArgs);
        }
        
        public void CheckCriticalHit(GroundDetector.GroundChangedEventArgs groundChangedEventArgs)
        {
            Transform detectorTransform = groundChangedEventArgs.GroundDetector.transform;
            if (groundChangedEventArgs.LandedCollider is not BoxCollider2D boxCollider2D)
            {
                return;
            }
            
            float detectorPosX = detectorTransform.position.x;
            float colliderLeftBorderX = boxCollider2D.bounds.min.x;
            float colliderRightBorderX = boxCollider2D.bounds.max.x;
            
            // Debug.Log($"collider dist: left {colliderLeftBorderX}, right {colliderRightBorderX}, detector {detectorPosX}");

            float minDist = Mathf.Min(detectorPosX - colliderLeftBorderX, colliderRightBorderX - detectorPosX);
            if (minDist <= _minCriticalHitDist)
            {
                var hitBubble = boxCollider2D.GetComponentInParent<Bubble>();
                hitBubble.ShowCriticalHitEffect();
                
                criticalEffect.transform.position = groundChangedEventArgs.GroundDetector.transform.position;
                criticalEffect.Play();
                AudioPlayer.Instance.PlaySound(criticalHitSound);
                CriticalHit?.Invoke();
            }
        }
    }
}